﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using Intorise.Common;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using System.Web;
using System.Threading;
using System.Net.Sockets;

namespace Model
{
    public class YyBotEngine : BotEngine
    {
        public YyBotEngine(Player player) : base(player) { }

        public override bool Login()
        {
            string loginUrl = "http://udblogin.duowan.com/login.do?game=DTSZJ&server={0}&report_ver=new&from=webyygame&rso=webyygame&webyygame&pro=webyygame&ref=GW&ref_desc=%E5%AE%98%E7%BD%91&showtools=0";
            string checkCodeUrl = "https://cas.sdo.com/authen/checkCodeLogin.jsonp?callback=checkCodeLogin_JSONPMethod&guid={0}&password={1}&appId=10&areaId=1&serviceUrl=http%3A%2F%2Favd.qidian.com%2FOALoginJump.aspx%3FReturnUrl%3Dhttp%253a%252f%252fgame.qidian.com%252fgame%252fdtszj%252flogin.aspx%26sitetype%3D9999&productVersion=v5&frameType=3&locale=zh_CN&version=21&tag=20&authenSource=2&productId=2&_={2}";

            CookieContainer cookies = new CookieContainer();
            ConsoleBLL.WriteLine(player + " 开始登录...");
            var request = net.SendRequest(string.Format(loginUrl, player.ServerID), "GET", cookies);
            var response = (HttpWebResponse)request.GetResponse();
            var html = net.GetResponseHtmlGzip(response);

            request = net.SendRequest("http://udblogin.duowan.com/ext/isLogin.do?callback=jQuery18209325693133287132_1421766205129&_=" + DateTime.Now.ToFileTime(), "GET", cookies);
            html = net.GetResponseHtml(request);

            request = net.SendRequest(string.Format("http://lgn.yy.com/lgn/oauth/p/noticeaccess.do?jsoncallback=jQuery_callback&callbackURL=http%3A%2F%2Fudblogin.duowan.com%2Flogin.do%3Fgame%3DDTSZJ%26server%3Ds{0}%26report_ver%3Dnew%26from%3Dwebyygame%26rso%3Dwebyygame%26webyygame%26pro%3Dwebyygame%26ref%3DGW%26ref_desc%3D%25E5%25AE%2598%25E7%25BD%2591%26showtools%3D0&_={1}", player.ServerID, DateTime.Now.ToFileTime()), "GET", cookies);
            html = net.GetResponseHtml(request);
            html = html.Replace("jQuery_callback(", "").Replace(")", "");
            JObject result = (JObject)JsonConvert.DeserializeObject(html);

            if (result["success"].ToString() != "1")
            {
                ConsoleBLL.WriteLineError(player + " 登录失败，注册错误");
                ConsoleBLL.WriteLine(html.ToString());
                return false;
            }

            string oauth_token = Tools.SubString(result["url"].ToString(), "oauth_token=", true);
            request = net.SendRequest(string.Format("https://lgn.yy.com/lgn/oauth/authorize.do?oauth_token={0}&rdm=0.20726223872043192&UIStyle=xqlogin", oauth_token), "GET", cookies);
            html = net.GetResponseHtmlGzip(request);

            request = net.SendRequest("https://lgn.yy.com/lgn/oauth/x/s/login_asyn.do", "POST", cookies);
            var postData = @"username={0}&password={1}&oauth_token={2}&denyCallbackURL=&UIStyle=xqlogin&appid=5188&cssid=5188&isRemMe=0";
            net.PostData(string.Format(postData, player.AccountName, player.PlayerAccount.Password, oauth_token), request);
            html = net.GetResponseHtml(request);
            result = (JObject)JsonConvert.DeserializeObject(html);

            if (result["code"].ToString() != "0")
            {
                ConsoleBLL.WriteLineError(player + " 登录失败");
                ConsoleBLL.WriteLine(html.ToString());
                return false;
            }

            string url = result["obj"]["callbackURL"].ToString();
            request = net.SendRequest(url, "GET", cookies);
            html = net.GetResponseHtmlGzip(request);

            url = Tools.SubString(html, "writeCrossmainCookieWithCallBack(\"", "\"", true);
            request = net.SendRequest(url, "GET", cookies);
            html = net.GetResponseHtml(request);

            url = Tools.SubString(html, "src=\"", "\"", true);
            request = net.SendRequest(url, "GET", cookies);
            html = net.GetResponseHtml(request);

            request = net.SendRequest(url, "GET", cookies);
            html = net.GetResponseHtml(request);

            url = "http://udblogin.duowan.com/login.do?game=DTSZJ&server=s{0}&report_ver=new&from=webyygame&rso=webyygame&webyygame&pro=webyygame&ref=GW&ref_desc=%E5%AE%98%E7%BD%91&showtools=0";
            request = net.SendRequest(string.Format(url, player.ServerID), "GET", cookies);
            html = net.GetResponseHtmlGzip(request);

            url = Tools.SubString(html, "src='http://api.duowandts.6ght.com/login/", "'", true);
            url = "http://api.duowandts.6ght.com/login/" + url;
            if (infoLog)
            {
                ConsoleBLL.WriteLineInfo(player + " login enterGameUrl:" + request.RequestUri);
            }

            request = net.SendRequest(url, "GET", cookies);
            response = (HttpWebResponse)request.GetResponse();
            url = response.Headers["location"];
            if (string.IsNullOrEmpty(url))
            {
                ConsoleBLL.WriteLineError(player + " 无法获取服务地址，html:");
                ConsoleBLL.WriteLine(html);
                return false;
            }
            url = "http://api.duowandts.6ght.com" + url.Remove(0, 2);

            request = net.SendRequest(url, "GET", cookies);
            html = net.GetResponseHtmlGzip(request);
            port = GameHelper.GetPort(html);
            if (port == 0)
            {
                ConsoleBLL.WriteLineError(player + " 无法获取服务器端口，html:");
                ConsoleBLL.WriteLine(html);
                return false;
            }
            head = new byte[] { 0x00, 0x01, 0x87, 0x70 };
            serverNo = Tools.GetAscII(player.PlayerAccount.ServerID);
            accountData = Tools.GetAscII(Tools.SubString(url, "user_name=", "&", true));
            time = Tools.GetAscII(GameHelper.GetTime(html));
            singn = Tools.GetAscII(GameHelper.GetSign(html));
            ip = GameHelper.GetIP(html);

            return true;
        }

        public override bool EnterGameServer()
        {
            DateTime startTime = DateTime.Now;
            Client = new TcpClient(ip, 843);
            var data = Tools.GetAscII("<policy-file-request/>\0");
            net.SendData(Client, data);
            Client.Close();

            Client = new TcpClient(ip, port);
            Begin();

            data = Tools.Contact(head, DataPackager.GetNetworkData((short)serverNo.Length), serverNo, net.GetNetworkBytes((short)accountData.Length), accountData, new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x0A }
                , time, new byte[] { 0x00, 0x01, 0x31, 0x00, 0x20 }, singn
                , new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x35, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x2d, 0x31, 0x00, 0x01, 0x30 });
            data = Tools.Contact(net.GetNetworkBytes(data.Length), data);
            net.SendData(Client, data, data.Length);

            while (!player.Entered)
            {
                Thread.Sleep(500);
                if (player.Config.TimeoutLogin < (DateTime.Now - startTime).TotalSeconds) { break; }
            }

            if (!player.Entered)
            {
                ConsoleBLL.WriteLineWaring(player + " 进入游戏超时！");
                Stop();
            }
            return player.Entered;
        }
    }
}
